package graph;

import javax.swing.plaf.IconUIResource;

//岛屿数量
public class leetcode200 {
    public static void main(String[] args) {
        char[][] graph = {{'1','1','1','1','0'}, {'1','1','0','1','0'}, {'1','1','0','0','0'}, {'0','0','0','0','0'}};
        printNums(graph);
        System.out.println(numIslands(graph));
    }

    public static void printNums(char[][] nums){
        for (int i = 0; i < nums.length; i++) {
            for(int j = 0; j < nums[0].length; j++){
                System.out.print(nums[i][j] + "\t");
            }
            System.out.println();
        }
    }

    public static int numIslands(char[][] grid) {
        if(grid == null || grid.length == 0) return 0;

        int num = 0;
        for(int i = 0; i < grid.length; i++){
            for (int j = 0; j < grid[0].length; j++) {
                if(grid[i][j] == '1'){
                    num++;
                    dfs(grid, i, j);
                }
            }
        }

        return num;
    }

    public static void dfs(char[][] grid, int i, int j){
        int row = grid.length;
        int col = grid[0].length;

        if(i < 0 || j < 0 || i >= row || j >= col || grid[i][j] == '0') return;

        grid[i][j] = '0';
        dfs(grid, i - 1, j);
        dfs(grid, i, j - 1);
        dfs(grid, i, j + 1);
        dfs(grid, i + 1, j);
    }
}
